<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css" integrity="sha256-2H3fkXt6FEmrReK448mDVGKb3WW2ZZw35gI7vqHOE4Y=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Gemini","version":"8.7.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="思考代码为什么会打印 6 个 6 123456let i &#x3D; 0;for(i &#x3D; 0; i &lt; 6; i++) &amp;#123;	setTimeout( () &#x3D;&gt; &amp;#123;        console.log(i)    &amp;#125;, 0);&amp;#125;;  分析在上面代码中，for 循环是同步代码，setTimeout 是异步代码，JS 按照从上到下的执行顺序执行同步代码，而异">
<meta property="og:type" content="article">
<meta property="og:title" content="JS函数的执行时机">
<meta property="og:url" content="http://example.com/2021/09/07/35/index.html">
<meta property="og:site_name" content="Xiaolong&#39;s Blog">
<meta property="og:description" content="思考代码为什么会打印 6 个 6 123456let i &#x3D; 0;for(i &#x3D; 0; i &lt; 6; i++) &amp;#123;	setTimeout( () &#x3D;&gt; &amp;#123;        console.log(i)    &amp;#125;, 0);&amp;#125;;  分析在上面代码中，for 循环是同步代码，setTimeout 是异步代码，JS 按照从上到下的执行顺序执行同步代码，而异">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-09-07T15:50:35.000Z">
<meta property="article:modified_time" content="2021-09-07T15:54:46.029Z">
<meta property="article:author" content="Xiaolong">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/09/07/35/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"http://example.com/2021/09/07/35/","path":"2021/09/07/35/","title":"JS函数的执行时机"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>JS函数的执行时机 | Xiaolong's Blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">Xiaolong's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%9D%E8%80%83"><span class="nav-number">1.</span> <span class="nav-text">思考</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">1.1.</span> <span class="nav-text">分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%E4%B8%80-let"><span class="nav-number">1.2.</span> <span class="nav-text">解决方法一 let</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%E4%BA%8C-%E4%BD%BF%E7%94%A8%E7%AB%8B%E5%8D%B3%E6%89%A7%E8%A1%8C%E5%87%BD%E6%95%B0%EF%BC%8C%E5%8D%B3%E9%97%AD%E5%8C%85"><span class="nav-number">1.3.</span> <span class="nav-text">解决方法二 使用立即执行函数，即闭包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%E4%B8%89-setTimeout-%E7%AC%AC%E4%B8%89%E4%B8%AA%E5%8F%82%E6%95%B0"><span class="nav-number">1.4.</span> <span class="nav-text">解决方法三 setTimeout 第三个参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%E5%9B%9B-try-catch"><span class="nav-number">1.5.</span> <span class="nav-text">解决方法四 try catch</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JS%E6%89%A7%E8%A1%8C%E6%9C%BA%E5%88%B6"><span class="nav-number">2.</span> <span class="nav-text">JS执行机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%A7%E8%A1%8C%E6%A0%88"><span class="nav-number">3.</span> <span class="nav-text">执行栈</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BB%E7%BA%BF%E7%A8%8B"><span class="nav-number">4.</span> <span class="nav-text">主线程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JS-%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E7%9A%84%E8%BF%90%E8%A1%8C%E6%9C%BA%E5%88%B6"><span class="nav-number">5.</span> <span class="nav-text">JS 异步执行的运行机制</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-overview">
            <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Xiaolong"
      src="/images/lion.jpg">
  <p class="site-author-name" itemprop="name">Xiaolong</p>
  <div class="site-description" itemprop="description">Never stop learning</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">45</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/drwna" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;drwna" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



          </div>
        </div>
      </div>
        <div class="back-to-top animated" role="button" aria-label="Back to top">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/Drwna" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/07/35/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/lion.jpg">
      <meta itemprop="name" content="Xiaolong">
      <meta itemprop="description" content="Never stop learning">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Xiaolong's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JS函数的执行时机
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-09-07 23:50:35" itemprop="dateCreated datePublished" datetime="2021-09-07T23:50:35+08:00">2021-09-07</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="思考"><a href="#思考" class="headerlink" title="思考"></a>思考</h2><p>代码为什么会打印 6 个 6</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">6</span>; i++) &#123;</span><br><span class="line">	<span class="built_in">setTimeout</span>( <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(i)</span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h3><p>在上面代码中，for 循环是同步代码，setTimeout 是异步代码，JS 按照从上到下的执行顺序执行同步代码，而异步代码被插入到任务队列中。</p>
<p>当执行完同步代码（for 循环），JS 会去执行异步代码（setTimeout）。</p>
<p>在每次 for 循环中，都将异步代码（setTimeout）放入任务队列中，所以任务队列中有 6 个 setTimeout 即有 6 个 <code>console.log(i)</code>。</p>
<p>在每次 for 循环中将 setTimeout 里的代码 <code>console.log(i)</code> 放入任务队列时，i 的值是不一样的，当 JS 引擎开始执行任务队列中代码时，会在当前作用域中找变量 i ，但当前 for 循环的作用域中没有对变量 i 的进行定义，这个时候会在创造该函数的作用域中寻找 i，找到的是 let i，这时的 i 时全局变量，并且值已经确定为 6。所以打印出 6 个 6。</p>
<p>执行流程：</p>
<p><code>for(i=0) ==&gt; for(i=1) ==&gt; for(i=2) ==&gt; for(i=3) ==&gt; for(i=4) ==&gt; for(i=5) ==&gt; for(i=6) ==&gt; console.log(6)x6</code></p>
<h3 id="解决方法一-let"><a href="#解决方法一-let" class="headerlink" title="解决方法一 let"></a>解决方法一 let</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>( <span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">6</span>; i++ )&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>( <span class="function">()=&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(i);</span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>let 的作用域是块作用域，能作用到 for 循环的子块中。</p>
<p>let 的作用于是块作用域，所以 setTimeout 被放到 任务队列的同时，<strong>let 定义的 i 值 也会跟随 setTimeout 进入队列</strong>。所以每次循环后队列里的 setTimeout 里的 i 值是不一样的。而 var 定义的 i 是无法进入的。（浅显易懂）</p>
<p>for 循环头部的 let 不仅将 i 绑定到 for 循环中，事实上它将其重新绑定到循环体的每一次迭代中，确保上一次迭代结束的值被重新赋值。setTimeout 里面的函数属于一个新的域，通过 var 定义的变量或全局变量是无法传入到这个函数执行，通过使用 let 来声明块变量能作用于这个块，所以箭头函数就能使用 i 这个变量，所以每次的 i 值不一样。</p>
<h3 id="解决方法二-使用立即执行函数，即闭包"><a href="#解决方法二-使用立即执行函数，即闭包" class="headerlink" title="解决方法二 使用立即执行函数，即闭包"></a>解决方法二 使用立即执行函数，即闭包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>( i = <span class="number">0</span>; i &lt; <span class="number">6</span>; i++)&#123;</span><br><span class="line">    (<span class="keyword">function</span> (<span class="params">j</span>)&#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>( <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(j);</span><br><span class="line">   		&#125;, <span class="number">0</span>);</span><br><span class="line">    &#125;)(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为 setTimeout 是异步执行，所以让它立即执行就可以了。</p>
<p>通过闭包，将 i 的变量驻留在内存中，当输出 j 时，引用的是外部函数的变量值 i，i 的值是根据循环来的，执行 setTimeout 时已经确定了里面的的输出了。</p>
<h3 id="解决方法三-setTimeout-第三个参数"><a href="#解决方法三-setTimeout-第三个参数" class="headerlink" title="解决方法三 setTimeout 第三个参数"></a>解决方法三 setTimeout 第三个参数</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">6</span>; i++)&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>( <span class="function">(<span class="params">i</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(i);</span><br><span class="line">    &#125;, <span class="number">0</span>, i);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 将每次的 i 值传入作用域。</span></span><br></pre></td></tr></table></figure>



<h3 id="解决方法四-try-catch"><a href="#解决方法四-try-catch" class="headerlink" title="解决方法四 try catch"></a>解决方法四 try catch</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">6</span>; i++)&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> i</span><br><span class="line">    &#125;<span class="keyword">catch</span>(i)&#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>( <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(i)</span><br><span class="line">        &#125;, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 将 i 作为异常抛出，传递给 setTimeout</span></span><br></pre></td></tr></table></figure>





<h2 id="JS执行机制"><a href="#JS执行机制" class="headerlink" title="JS执行机制"></a>JS执行机制</h2><p>首先，JS是单线程环境，代码从上到下依次执行。这种执行方这也被称作是“同步执行”。（同一时间 JS 只能执行一段代码，如果这段代码要执行很长时间，那么之后的代码只能尽情地等待它执行完才能执行）。</p>
<p>但 JS 中引进了异步机制。于是，所有任务可以分成两种，一种是同步任务（synchronous），另一种是异步任务（asynchronous）。</p>
<p><strong>同步任务</strong>指的是，在主线程上排队执行的任务，只有前一个任务执行完毕，才能执行后一个任务；</p>
<p><strong>异步任务</strong>指的是，不进入主线程、而进入”任务队列”（task queue）的任务，只有主线程上的任务执行完了，才通知”任务队列”，任务队列中的任务才会进入主线程执行。</p>
<h2 id="执行栈"><a href="#执行栈" class="headerlink" title="执行栈"></a>执行栈</h2><p>当执行某个函数、用户点击一次鼠标，Ajax完成，一个图片加载完成等事件发生时，只要指定过回调函数，这些事件发生时就会进入任务队列中，等待主线程读取,遵循先进先出原则。</p>
<p>执行任务队列中的某个任务，这个被执行的任务就称为执行栈。</p>
<h2 id="主线程"><a href="#主线程" class="headerlink" title="主线程"></a>主线程</h2><p>要明确的一点是，主线程跟执行栈是不同概念，主线程规定现在执行执行栈中的哪个事件。</p>
<p>主线程循环：即主线程会不停的从执行栈中读取事件，会执行完所有栈中的同步代码。</p>
<p>当遇到一个异步事件后，并不会一直等待异步事件返回结果，而是会将这个事件挂在与执行栈不同的队列中，我们称之为任务队列(Task Queue)。</p>
<p><strong>当主线程将执行栈中所有的代码执行完之后，主线程将会去查看任务队列是否有任务</strong>。如果有，那么主线程会依次执行那些任务队列中的回调函数。</p>
<h2 id="JS-异步执行的运行机制"><a href="#JS-异步执行的运行机制" class="headerlink" title="JS 异步执行的运行机制"></a>JS 异步执行的运行机制</h2><ol>
<li>所有任务都在主线程上执行，形成一个执行栈。</li>
<li>主线程之外，还存在一个任务队列。只要异步任务有了运行结果，就在任务队列之中放置一个事件。</li>
<li>一旦执行栈中的所有同步任务执行完毕，系统就会读取任务队列。那些对应的异步任务，进入执行栈开始执行。</li>
<li>主线程不断重复上面的第三步。</li>
</ol>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/07/36/" rel="prev" title="异步与Promise">
                  <i class="fa fa-chevron-left"></i> 异步与Promise
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/09/08/14/" rel="next" title="跨域">
                  跨域 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Xiaolong</span>
</div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/third-party/search/local-search.js"></script>




  





</body>
</html>
